package com.zjw.forum.utils;

import com.zjw.forum.config.AppConfig;
import com.zjw.forum.model.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@SpringBootTest
public class JWTUtils {
    private static final long Expiration=5*10000;
    private static final String KEY="65SXSDuBWwszPOkoAEJPkSkI3OD/iURwwZsgX6iPXFY=";
    private static final Key keys=Keys.hmacShaKeyFor(Decoders.BASE64.decode(KEY));
    /**
     * 生成立牌
     * @return
     */
    @Test
    public void genToken(){
        //准备一个User测试
        User user=new User();
        user.setUsername("wzj");
        user.setNickname("wang");
        user.setPassword("123");

        //填写负载信息
        Map<String,Object> map=new HashMap<>();
        map.put(AppConfig.USER_SESSION,user);
        //生成字符串签名key（根据这个key生成令牌）

        System.out.println(Jwts.builder().signWith(keys).setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis()+Expiration))
                .compact());
    }
    //生成字符串key
    @Test
    public void genKey(){
        SecretKey secretKey=Keys.secretKeyFor(SignatureAlgorithm.HS256);
        String encode= Encoders.BASE64.encode(secretKey.getEncoded());
        System.out.println(encode);
    }

    //校验token
    @Test
    public void verify(){
        //前端传token过来
        String token="eyJhbGciOiJIUzI1NiJ9.eyJVU0VSX1NFU1NJT04iOnsiaWQiOm51bGwsInVzZXJuYW1lIjoid3pqIiwibmlja25hbWUiOiJ3YW5nIiwicGhvbmVOdW0iOm51bGwsImVtYWlsIjpudWxsLCJnZW5kZXIiOm51bGwsImF2YXRhclVybCI6bnVsbCwiYXJ0aWNsZUNvdW50IjpudWxsLCJpc0FkbWluIjpudWxsLCJyZW1hcmsiOm51bGwsInN0YXRlIjpudWxsLCJjcmVhdGVUaW1lIjpudWxsLCJ1cGRhdGVUaW1lIjpudWxsfSwiZXhwIjoxNzQxODY1NDE3fQ.mJIyz3S8l0KpcqfQWWcESxkQTu7JxtSCaBaob_tD7Sk";
        JwtParser build=Jwts.parserBuilder().setSigningKey(keys).build();
        Claims body=build.parseClaimsJws(token).getBody();
    }
}
